<template>
  <div class="organization">
    <van-nav-bar
      left-text="返回"
      fixed="true"
      title="选择学校或机构"
      safe-area-inset-top="true"
      :border="true"
      left-arrow
      @click-left="onClickLeft"
    />
    <div>
      <div class="divtitle">请选择学校或机构</div>
      <van-cell-group>
        <van-cell
          v-for="item in state.list"
          :key="item.tenantId"
          :title="item.tenantName"
          is-link
          @click="selectOrg(item.tenantId)"
        />
      </van-cell-group>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { findTenList, changeTenant } from '/@/api/login/login'
import { setToken, setUser } from '/@/util/auth'
import { useStore } from '/@/store'
import { useLoginAfter } from '/@/views/login/utils'

export default defineComponent({
  components: {},
  setup(props, context) {
    const router = useRouter()
    const { commit } = useStore()

    const { loginRedirect } = useLoginAfter()

    const state = reactive({
      value: '',
      list: JSON.parse(localStorage.getItem('fock_user_list') || '[]'),
    })

    const successFn = async function (res: any) {
      const loginfo: any = res.data.data
      setToken(loginfo.accessToken)
      const user = {
        account: loginfo.account,
        tenantId: loginfo.tenantId,
        userId: loginfo.userId,
        userName: loginfo.userName,
      }
      setUser(JSON.stringify(user))
      commit('setUser', user)
      await loginRedirect()
    }

    return {
      state,
      onClickLeft: function () {
        router.push({
          name: 'Login',
          params: {},
        })
      },
      onSearch() {
        const query = state.value
        findTenList(query).then((res) => {
          const list = res.data.data || []
          state.list = list
        })
      },
      selectOrg(tenantId: any) {
        const query = router.currentRoute.value.query
        const loginfo = JSON.parse(localStorage.getItem('fock_user_data') || '')
        const param = {
          roles: loginfo.authority.split(','),
          oauthId: loginfo.oauthId,
          user: {
            id: loginfo.userId,
            tenantId: tenantId,
            name: loginfo.userName,
            realName: loginfo.userName,
            account: loginfo.account,
            gradeId: loginfo.gradeId,
          },
        }
        changeTenant(param).then((res) => {
          successFn(res)
        })
      },
    }
  },
})
</script>

<style lang="less" scoped>
.organization {
  box-sizing: border-box;
  width: 100%;
  min-height: 100vh;
  padding-top: 46px;
  padding-bottom: 50px;
  background-color: #fff;

  .divtitle {
    font-size: 20px;
    margin: 15px;
  }
}
</style>
